package com.ncmmall.mall.controller.business.freight;

import com.ncmmall.application.business.merchant.freight.MerchantFreightApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.merchant.freight.MerchantFreight;
import com.ncmmall.domain.business.merchant.freight.MerchantFreightCity;
import com.ncmmall.domain.business.merchant.freight.MerchantFreightProvince;
import com.ncmmall.domain.business.merchant.freight.MerchantFreightTemplate;
import com.ncmmall.domain.business.merchant.freight.QMerchantFreightTemplate;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商家运费模板设置
 *
 * @author likaikai
 * @date 2019-07-08 11:48
 */

@Controller
@RequestMapping("/supplier/freight")
public class FreightController {

    private Logger logger = LoggerFactory.getLogger(FreightController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MerchantFreightApplication freightApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 运费模板列表
     *
     * @param model
     * @param pageParams
     * @param merchantFreightTemplate
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, MerchantFreightTemplate merchantFreightTemplate) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        params.put("id", Securitys.currentUser().getId());
        String hql = builderSQL("select u from MerchantFreightTemplate u where u.merchant.id = :id ", params, merchantFreightTemplate);
        QueryPage<MerchantFreightTemplate> page = queryChannelService.findPage(hql, pageRequest.setParams(params), MerchantFreightTemplate.class);

        model.addAttribute("page", page).addAttribute("params", merchantFreightTemplate);

        return "supplier/freight/template/list";
    }

    private String builderSQL(String sql, Map<String, Object> params, MerchantFreightTemplate template) {


        if (!Strings.isNullOrEmpty(template.getName())) {
            sql += " and u.name like :name ";
            params.put("name", "%" + template.getName() + "%");
        }

        if (template.getType() > 0) {
            sql += " and u.type = :type ";
            params.put("type", template.getType());
        }

        if (template.getStatus() > 0) {
            sql += " and u.status = :status ";
            params.put("status", template.getStatus());
        }

        return sql;
    }

    /**
     * 添加运费模板
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    private String create(Model model) {

        MerchantFreightTemplate template = new MerchantFreightTemplate();

        model.addAttribute("_method", "POST").addAttribute("template", template);

        return "supplier/freight/template/form";
    }

    /**
     * 添加运费模板
     *
     * @param requestWith
     * @param goods
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> create(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, MerchantFreightTemplate template) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(Securitys.currentUser().getId()), WebUser.class);
            freightApplication.create(merchant, template);
            logApplication.eventOfMerchant(Securitys.currentUser(), "添加运费模板", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[添加运费模板异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 禁用运费模板
     *
     * @param request
     * @param requestWith
     * @param template
     * @return
     */
    @RequestMapping(value = "/disable", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> disable(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, MerchantFreightTemplate template) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            freightApplication.disable(template);
            logApplication.eventOfMerchant(Securitys.currentUser(), "禁用运费模板", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[添加运费模板异常]", e);
            return ImmutableMap.of("status", false);

        }
    }


    /**
     * 启用运费模板
     *
     * @param request
     * @param requestWith
     * @param template
     * @return
     */
    @RequestMapping(value = "/enabled", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> enabled(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, MerchantFreightTemplate template) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            freightApplication.enabled(template);
            logApplication.eventOfMerchant(Securitys.currentUser(), "启用运费模板", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[添加运费模板异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 编辑运费模板
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.GET)
    private String modify(@PathVariable("id") long id, Model model) {
        MerchantFreightTemplate template = queryChannelService.findOne(QMerchantFreightTemplate.merchantFreightTemplate.id.eq(id), MerchantFreightTemplate.class);
        List<MerchantFreight> merchantFreights = queryChannelService.findAll("select f from MerchantFreight f where f.template.id = :id and f.parent is null ", ImmutableMap.of("id", id), MerchantFreight.class);
        for (MerchantFreight freight : merchantFreights) {
            freight.setCitys(freight.getMerchantFreights().stream().map(MerchantFreight::getCity).collect(Collectors.joining("-")));
        }

        model.addAttribute("template", template).addAttribute("merchantFreights", merchantFreights).addAttribute("_method", "PUT");
        return "supplier/freight/template/form";
    }

    /**
     * 编辑运费模板
     *
     * @param requestWith
     * @param template
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, MerchantFreightTemplate template) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(Securitys.currentUser().getId()), WebUser.class);
            freightApplication.modify(merchant, template);
            logApplication.eventOfMerchant(Securitys.currentUser(), "修改运费模板", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[添加运费模板异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 选择省市弹窗
     *
     * @param model
     * @param note
     * @return
     */
    @RequestMapping(value = "/province", method = RequestMethod.GET)
    public String province(Model model, String note) {
        model.addAttribute("note", note);
        List<MerchantFreightProvince> provinces = queryChannelService.queryAllEntity("select * from mall_merchant_freight_province", Collections.emptyMap(), MerchantFreightProvince.class);
        for (MerchantFreightProvince province : provinces) {
            List<MerchantFreightCity> citys = queryChannelService.queryAllEntity("select * from mall_merchant_freight_city where provinceCode = :pCode", ImmutableMap.of("pCode", province.getProvinceCode()), MerchantFreightCity.class);
            province.setMerchantFreightCities(citys);
        }
        model.addAttribute("provinces", provinces);
        return "supplier/freight/province";
    }
}
